package com.ruoyi.websocket.handler;


import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.websocket.domain.DTO.WeChatMessageDTO;
import com.ruoyi.websocket.domain.DTO.WeChatTextDTO;
import com.ruoyi.websocket.domain.WbNoticeMessage;
import com.ruoyi.websocket.service.IWbNoticeMessageService;
import com.ruoyi.websocket.service.impl.WxService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.*;

/**
 * 消息推送 WebSocket Handler
 */
@Component
public class PushMessageWebsocketHandler extends TextWebSocketHandler {

    @Autowired
    private IWbNoticeMessageService wbNoticeMessageService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private WxService wxService;

    private static final Logger logger = LoggerFactory.getLogger(PushMessageWebsocketHandler.class);

    // 存储所有连接的会话
    private final Set<WebSocketSession> sessions = Collections.synchronizedSet(new HashSet<>());

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        JSONObject jsonObject = JSONObject.parseObject(payload);

        String type = jsonObject.getString("type");
        if ("ping".equalsIgnoreCase(type)) {
            session.sendMessage(new TextMessage("{\"type\":\"pong\"}"));
            return;
        }

        if ("refresh".equalsIgnoreCase(type)) {
            broadcast(payload);
            return;
        }

        // 获取用户信息
        String userId = (String) session.getAttributes().get("userId");
        String nickName = (String) session.getAttributes().get("nickName");

        // 提取data所需的字段
        JSONObject data = jsonObject.getJSONObject("data");
        String title = data.getString("title");
        String content = data.getString("content");
        Long receiverId = data.getLong("receiverId");
        String receiverName = data.getString("receiverName");

        // 1. 保存消息到数据库
        String receiverWxId = saveMessages(userId, nickName, title, content, receiverId, receiverName);

        // 2. 广播给所有在线客户端
        broadcast(payload);

        // 3. 推送到企业微信
//        wxService.sendWeChatNotification(title, content, receiverWxId);

        // 4. 推送邮箱等等、、、

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        exception.printStackTrace();
        sessions.remove(session);
        if (session.isOpen()) {
            session.close();
        }
    }

    /**
     * 广播消息到所有在线用户
     */
    private void broadcast(String payload) {
        for (WebSocketSession s : sessions) {
            if (s.isOpen()) {
                try {
                    s.sendMessage(new TextMessage(payload));
                } catch (IOException e) {
                    System.out.println("广播消息失败："+e);
                }
            }
        }
    }

    /**
     * 插入一条通知消息
     */
    private void insertMessage(Long senderId, String senderName, Long receiverId, String receiverName, String title, String content) {
        WbNoticeMessage msg = new WbNoticeMessage();
        msg.setTitle(title);
        msg.setContent(content);
        msg.setSenderId(senderId);
        msg.setSenderName(senderName);
        msg.setReceiverId(receiverId);
        msg.setReceiverName(receiverName);
        wbNoticeMessageService.insertWbNoticeMessage(msg);
    }

    /**
     * 保存消息到数据库，并返回企业微信接收人ID
     */
    private String saveMessages(String userId, String nickName, String title, String content, Long receiverId, String receiverName) {
        if (receiverId != null) {
            // 单发
            insertMessage(Long.parseLong(userId), nickName, receiverId, receiverName, title, content);

            SysUser sysUser = userMapper.selectUserById(receiverId);
            return sysUser != null ? sysUser.getWxEnterpriseId() : "";
        } else {
            // 群发
            List<SysUser> userList = userMapper.selectUserList(new SysUser());
            for (SysUser sysUser : userList) {
                insertMessage(Long.parseLong(userId), nickName, sysUser.getUserId(), sysUser.getNickName(), title, content);
            }
            return "@all";
        }
    }



}

